package com.example.tourism.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.tourism.config.AlipayConfig;
import com.example.tourism.mapper.OrderMapper;
import com.example.tourism.pojo.po.Orders;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayController {
    // 沙箱支付的网关
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";

    private static final String FORMAT = "json";

    private static final String CHARSET = "UTF-8";

    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AlipayConfig alipayConfig;
    @Autowired
    private OrderMapper orderMapper;

    @GetMapping("/pay")
    public void pay(String orderUid, HttpServletResponse response) throws IOException {
        // 先查询订单
        Orders orders = orderMapper.selectOrderByOrderUid(orderUid);
        if (orders == null) {
            return;
        }

        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, alipayConfig.getAppId(),
                alipayConfig.getAppPrivateKey(), FORMAT, CHARSET, alipayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 创建request 设计参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderUid);   // 订单号
        bizContent.put("total_amount", orders.getPrice());  // 订单金额
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");  // 支付方式
        bizContent.put("subject", "旅游订单");
        request.setBizContent(bizContent.toJSONString());
        request.setReturnUrl("http://localhost:5173/userInfo/order");

        // 调用支付接口
        String result = null;
        try {
            result = alipayClient.pageExecute(request).getBody();  // 获取支付结果
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();

    }


    @PostMapping("/notify")
    public void payNotify(HttpServletRequest request) throws  AlipayApiException {
        if(request.getParameter("trade_status").equals("TRADE_SUCCESS")){
            System.out.println("支付宝成功回调");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayConfig.getAlipayPublicKey(), CHARSET);

            if (checkSignature) {
               // 验证通过
                System.out.println("交易名称："  + params.get("subject"));
                System.out.println("交易状态：" + params.get("trade_status"));
                System.out.println("交易金额：" + params.get("total_amount"));
                System.out.println("支付宝交易凭证号：" + params.get("trade_no"));
                System.out.println("订单号：" + params.get("out_trade_no"));
                System.out.println("买家支付宝唯一id：" + params.get("buyer_id"));
                System.out.println("买家付款时间：" + params.get("gmt_payment"));
                System.out.println("买家付款金额："+  params.get("buyer_pay_amount"));

                String orderUid = params.get("out_trade_no");
                // 更新订单状态
                orderMapper.updateOrderStatus(orderUid);
            }
        }

    }


}
